package com.candy.service;

import com.candy.dao.PermissionMapper;
import com.candy.dao.RoleMapper;
import com.candy.dao.UserMapper;
import com.candy.entity.Permission;
import com.candy.entity.Role;
import com.candy.entity.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class LoginUserService implements UserDetailsService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Qualifier("getPw")
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //存放权限的
        Collection<GrantedAuthority> authorities = new ArrayList<>();

        System.out.println("自定义登录");
        //1、根据用户名去数据库查询，如果不存在抛出 UserNameNotFoundExeption异常
        UserVo userVo=userMapper.selectBYUserName(username);

        if(userVo==null){
            System.out.println("用户名不存在");
            throw new UsernameNotFoundException("用户名不存在");
        }
        //因为数据库中目前存放的是明文，一般在注册的时候都会加密，这里我就手动加密了
        String password=passwordEncoder.encode(userVo.getPassword());
        //拿到用户角色
        List<Role> roles=roleMapper.selectByUserId(userVo.getUid());
        for(Role role: roles){
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            //拿到用户具有的权限
            List<Permission> permissionList=permissionMapper.selectByRoleId(role.getRid());
            for (Permission permission:permissionList){
                //添加到
                authorities.add(new SimpleGrantedAuthority(permission.getStr()));
            }
        }

        return new User(username,password,authorities);
    }
}